package com.qingmu.club.minaapi.wechat;

import com.alibaba.fastjson.JSONObject;
import com.qingmu.club.minaapi.model.AccessToken;
import com.qingmu.club.minaapi.model.TemplateData;
import com.qingmu.club.minaapi.model.WxMssVo;
import com.qingmu.club.minaapi.utils.CommonException;
import com.qingmu.club.minaapi.utils.HttpUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信相关接口
 *
 * @Author: duke
 * @Date: 2019-08-08 17:21
 */
public class WechatUtil {


    //会员端小程序
    public static String memberAppId = "wx5c4aa70784aa6e2c";
    public  static String memberAppSecret = "4bc7fefef3764ef07374a85cffa2bbfd";

    //俱乐部端小程序
    public static String clubAppId = "wxc63e1ae4e35851f0";
    public  static String clubAppSecret = "1d5716f8db03971be2881a3d4e185b46";

//    public static JSONObject getSessionKeyOrOpenId(String code) {
//        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
//        Map<String, String> requestUrlParam = new HashMap<>();
//        // https://mp.weixin.qq.com/wxopen/devprofile?action=get_profile&token=164113089&lang=zh_CN
//        //小程序appId
//        requestUrlParam.put("appid", memberAppId);
//        //小程序secret
//        requestUrlParam.put("secret", memberAppSecret);
//        //小程序端返回的code
//        requestUrlParam.put("js_code", code);
//        //默认参数
//        requestUrlParam.put("grant_type", "authorization_code");
//        //发送post请求读取调用微信接口获取openid用户唯一标识
//        try {
//            String result = HttpUtils.requestPostForm(requestUrl, requestUrlParam, null);
//            JSONObject jsonObject = JSON.parseObject(result);
//            return jsonObject;
//        } catch (CommonException e) {
//            e.printStackTrace();
//        }
//
//        return null;
//
//    }

    /**
     * 生成人员二维码
     * @param uploadPath
     * @param staffShopId
     * @return
     */
    public static String createMiniQrcode(String uploadPath, String staffShopId){

        //小程序支付
//         String xcxAppId ="wx1319467c691fcb82";
//
//         String xcxAppSecret ="344dab6e3c7178ce7537ffd346367dd8";

        String accessToken = getAccess_token(memberAppId,memberAppSecret);
        String miniFilePath = QrCodeUtil.createQrCode(staffShopId, accessToken, uploadPath);
        if (miniFilePath == null) {
            return null;
        }

        return miniFilePath;

    }


//    /**
////     * 生成积分商品二维码
////     * @param uploadPath
////     * @param goodsShopId
////     * @return
////     */
////    public static String createMiniQrcode2(String uploadPath, String goodsShopId){
////
////
////        String accessToken = getAccess_token(memberAppId,memberAppSecret);
////        String miniFilePath = QrCodeUtil.createGoodsQrCode(goodsShopId, accessToken, uploadPath);
////        if (miniFilePath == null) {
////            return null;
////        }
////
////        return miniFilePath;
////
////    }


    public static String getAccess_token(String appid, String appsecret) {
        //获取access_token
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + appid + "&secret=" + appsecret;
        try {
            String json = HttpUtils.requestGet(url, null, null);
            AccessToken accessToken = JSONObject.parseObject(json, AccessToken.class);
            return accessToken.getAccess_token();
        } catch (CommonException e) {
            e.printStackTrace();
            return "";
        }
    }
//
//    public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
//        //String skey = UUID.randomUUID().toString();
//        // 被加密的数据
//        byte[] dataByte = Base64.decode(encryptedData);
//        // 加密秘钥
//        byte[] keyByte = Base64.decode(sessionKey);
//        // 偏移量
//        byte[] ivByte = Base64.decode(iv);
//        try {
//            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
//            int base = 16;
//            if (keyByte.length % base != 0) {
//                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
//                byte[] temp = new byte[groups * base];
//                Arrays.fill(temp, (byte) 0);
//                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
//                keyByte = temp;
//            }
//            // 初始化
//            Security.addProvider(new BouncyCastleProvider());
//            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
//            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
//            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
//            parameters.init(new IvParameterSpec(ivByte));
//            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
//            byte[] resultByte = cipher.doFinal(dataByte);
//            if (null != resultByte && resultByte.length > 0) {
//                String result = new String(resultByte, "UTF-8");
//                return JSON.parseObject(result);
//            }
//        } catch (Exception e) {
//        }
//        return null;
//    }

    /*
     * 微信小程序推送单个用户
     * */
    public String pushOneUser(String openid, String formid) {


        //获取access_token
        String access_token = getAccess_token("appid", "APPSECRET");
        String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send" +
                "?access_token=" + access_token;

        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openid);//用户openid
        wxMssVo.setTemplate_id("LzeDP0G5PLgHoOjCMfhu44wfUluhW11Zeezu3r_dC24");//模版id
        wxMssVo.setForm_id(formid);//formid


        Map<String, TemplateData> m = new HashMap<>(5);

        //keyword1：订单类型，keyword2：下单金额，keyword3：配送地址，keyword4：取件地址，keyword5备注
//        TemplateData keyword1 = new TemplateData();
//        keyword1.setValue("新下单待抢单");
//        m.put("keyword1", keyword1);
//
//        TemplateData keyword5 = new TemplateData();
//        keyword5.setValue("这里填备注");
//        m.put("keyword5", keyword5);
//        wxMssVo.setData(m);
//
//        String result = HttpUtils.requestPostForm(url,m,null);
//
//        ResponseEntity<String> responseEntity =restTemplate.postForEntity(url, wxMssVo, String.class);
//        log.error("小程序推送结果={}", responseEntity.getBody());
//        return responseEntity.getBody();
        return "";
    }
}
